import useMessage from "@/hooks/useMessage";
import { Form, Button, Input, FormInstance } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { addMessageApi, getMessageDetailApi, updateMessageApi } from "@/api/modules/system";
import { Message } from "@/api/interface/system";

interface PropsType {
	type?: string;
	messageId?: number;
	onComfirm?: () => void;
}

const MessageAdd: React.FC<PropsType> = props => {
	const { type, onComfirm, messageId } = props;
	const { contextHolder, success, error } = useMessage();

	const [messageDetail, setMessageDetail] = useState<any>({});

	const getMessageDetail = async () => {
		const res = await getMessageDetailApi(messageId!);
		if (res.code === 200) {
			setMessageDetail(res.data);
		}
	};

	const formRef = useRef<FormInstance | null>(null);

	const onFinish = async (message: Message) => {
		try {
			if (type && messageId) {
				await updateMessageApi({ ...message, id: messageId });
			} else {
				await addMessageApi(message);
			}
			onComfirm && onComfirm();
			formRef.current?.setFieldsValue({
				content: ""
			});
			success("发布成功");
		} catch (err) {
			error("发布失败");
		}
	};

	useEffect(() => {
		if (type) {
			getMessageDetail();
		}
	}, [messageId]);

	useEffect(() => {
		formRef.current?.resetFields();
		return () => {
			formRef.current?.setFieldsValue({
				content: ""
			});
		};
	}, [messageDetail]);

	return (
		<div>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={messageDetail}
			>
				<Form.Item label="内容" rules={[{ required: true }]} name="content">
					<Input />
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default MessageAdd;
